package com.huilan.hgt.controller;


import com.huilan.hgt.entity.Attachment;
import com.huilan.hgt.entity.Email;
import com.huilan.hgt.entity.User;
import com.huilan.hgt.service.AttachmentService;
import com.huilan.hgt.service.EmailService;
import com.huilan.hgt.service.UserService;
import com.huilan.hgt.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 邮件表 前端控制器
 * </p>
 *
 * @author ghy
 * @since 2018-11-02
 */
@Controller
@RequestMapping("/email")
public class EmailController {



    @Autowired
    private UserService userService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private AttachmentService attachmentService;


    /**
     * 跳转邮箱发送页面
     * @return
     */
    @GetMapping
    public String email(ModelMap modelMap){
        //查询邮箱列表
        List<User> users = userService.queryEmails();
        modelMap.put("users",users);
        modelMap.put("code",StringUtil.getUUID());
        return "/email/mail_compose";
    }

    /**
     * 发送邮件
     */
    @PostMapping(value = "/send.do")
    public String sendEmail(@Valid Email email, String code, HttpServletRequest request){
        String contextPath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();

        boolean isSend = emailService.sendMail(email,code,contextPath);
        System.out.println("发送邮件:" + isSend);
        return "redirect:/email/history.do";
    }


    /**
     * 邮件历史
     */
    @GetMapping(value = "/history.do")
    public String history(ModelMap modelMap){
        return "/email/mail_history";
    }


    /**
     * 邮件列表
     */
    @GetMapping(value = "/historyList.do")
    @ResponseBody
    public PageUtil historyList(PageUtil<Email> page){
        //查询邮件发送历史
        emailService.selectEmailHistory(page);
        return page;
    }


    /**
     * 邮件详情
     */
    @GetMapping("/mailDetail.do")
    public String  mailDetail(ModelMap modelMap,String emailId){
        Email email = emailService.getById(emailId);

        //根据邮件ID查询附件信息
        List<Attachment> attachmentList = attachmentService.queryAttachmentByEmailId(emailId);
        modelMap.put("email",email);
        modelMap.put("attachmentList",attachmentList);
        return "/email/mail_detail";
    }
}

